package com.he.hsdyc.common.token;

import com.he.hsdyc.common.ValidatedException;
import com.he.hsdyc.model.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;

/**
 * Created with IntelliJ IDEA.
 * User: jc
 * Date: 2019-06-14
 * Time: 15:47
 */
public class TokenUtils {

    public static User analysisToken(HttpServletRequest request){
        String header = request.getHeader("Authorization");
        String token = StringUtils.substringAfter(header,"Bearer ");
        Claims body = null;
        try {
            body = Jwts.parser().setSigningKey("internet_plus".getBytes("UTF-8"))
                    .parseClaimsJws(token).getBody();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new ValidatedException("用户信息获取失败");
        }

        Object id= body.get("id");
        String userName=(String) body.get("username");
        String name=(String) body.get("name");
        String icon=(String) body.get("icon");
        String tel=(String) body.get("tel");
        Boolean gender=(Boolean) body.get("gender");
        Integer roleName=(Integer) body.get("roleName");
        String auth=(String) body.get("auth");
        Integer subjectType=(Integer) body.get("subjectType");
        Boolean del=(Boolean) body.get("del");

        User user=new User();
        user.setId(Long.parseLong(id.toString()));
        user.setUsername(userName);
        user.setName(name);
        user.setIcon(icon);
        user.setTel(tel);
        user.setGender(gender);
        user.setRoleName(roleName);
        user.setAuth(auth);
        user.setSubjectType(subjectType);
        user.setDel(del);


        return user;


    }
    
}
